import {ChangeDetectorRef, Component, Input, OnInit} from '@angular/core';
import {FilterData} from "../filter-box/filter-box.component";
import {ModalController, NavController, PickerController} from "@ionic/angular";
import {ActivatedRoute, Router} from "@angular/router";
import {HttpService} from "../../services/http/http.service";
import {StorageService} from "../../services/storage.service";
import {NativeService} from "../../services/native.service";
import {API} from "../../services/API";
import {UserInfo} from "../../../models/UserInfo";
import {StorageKey} from "../../Constants";
import {SelectCommunityComponent} from "../select-community/select-community.component";
declare var  AMap: any;
@Component({
  selector: 'app-modify-information',
  templateUrl: './modify-information.component.html',
  styleUrls: ['./modify-information.component.scss'],
})
export class ModifyInformationComponent implements OnInit {
  option= '请选择';
  option1= '请选择';
  option2= '请选择';
  status: Array<FilterData> =[
    {
      id: '1',
      content: '是',
      isSelect: false,
    },
    {
      id: '0',
      content: '否',
      isSelect: false,
    },
  ];
  @Input() address; // 所在区域
  @Input() code; // 城市编码
  buildings = [];
  buildingId; // 楼栋编码
  buildingName = '';
  @Input() name;
  @Input() city;
  @Input() summaryId; // 传参id
  @Input() serialNo; // 传参id
  unitList = []; // 楼层列表
  unitId; // 楼层id
  houseList = []; // 房间号
  house = '';
  unitName = ''; // 房间名
  houseId; // 房间id
  @Input() province; // 省
  @Input() resiCity; // 市
  @Input() restDistrict; // 区
  @Input() flag;  // 传递类型 初审:trial  房产信息：select
  result = []; // 请求定位返回结果


  /********************表单字段************************/
  resiProivnce; // 小区所在省
  // resiCity; // 小区所在市
  // restDistrict; // 小区所在区
  resiAdd; // 小区地址
  resiLongitutd; // 小区经度
  resiLatitutd; // 小区纬度
  houseBuilding; // 所在楼栋
  houseUnit; // 所在单元
  houseNumber; // 所在户
  resiArea; // 面积
  haveBasement; // 是否有地下室（1:是 0:否） int
  floorArea; // 地上面积 double
  undergroundArea; // 地下面积 double
  builtYear; // 建成年份 int
  houseLocated; // 位置
  onlineEvaluation; // 在线评估价 BigDecimal
  maxCreditAvailable; // 最高可贷额度 BigDecimal
  inputTime; // 插入时间
  @Input() communityId; // 小区编号
  urlFlag = '1';
  constructor(
      private picker: PickerController,
      public cd: ChangeDetectorRef,
      private activatedRoute: ActivatedRoute,
      private httpService: HttpService,
      private router: Router,
      private nav: NavController,
      private storage: StorageService,
      private nativeService: NativeService,
      private modalCtrl: ModalController,
  ) {
    // let time = new Date(this.builtYear).getTime();
    // let datatime = new Date(time).toISOString();
    // this.builtYear =String(datatime.substring(0, datatime.length - 5)).replace('T', ' ');
    // console.log('打印建成年份');
    // console.log(this.builtYear);
  }

  ngOnInit() {
    this.selectBuilding();
  }

  // 根据小区获取楼栋
  async selectBuilding() {
    const param = {
      cityCode: this.code,
      communityId: this.communityId,
    }
    const info = await this.httpService.post(API.COMMUNITY_BUILDING, param, false);
    console.log(info);
    if (info.building.code == '0') {
      this.buildings = info.building.data;
      for (let item of this.buildings) {
        if (item.buildingId == this.buildingId){
          this.buildingName = item.buildingName;
        }
      }
    } else {
      this.nativeService.showAlert(info.building.message, '确定');
    }

  }
  // 根据楼栋获取楼层
  async selectUnit() {
    const param = {
      cityCode: this.code,
      communityId: this.communityId,
      buildingId: this.buildingId,
    };
    const info = await this.httpService.post(API.COMMUNITY_UNIT, param, false);
    console.log(info);
    if (info.unit.data.length > 0) {
      this.unitList = info.unit.data;
    }
  }
  // 根据楼层获取房号
  async selectHouse() {
    const param = {
      cityCode: this.code,
      unitId: this.unitId,
      buildingId: this.buildingId,
      communityId: this.communityId,
    };
    const info = await this.httpService.post(API.COMMUNITY_HOUSE, param, false);
    console.log(info);
    if (info.house.data.length) {
      this.houseList = info.house.data;
    }
  }
  getColumns(numColumns, numOptions, columnOptions) {
    const columns = [];
    for (let i = 0; i < numColumns; i++) {
      columns.push({
        name: `col`,
        options: this.getColumnOptions(i, numOptions, columnOptions)
      });
    }
    return columns;
  }

  getColumnOptions(columnIndex, numOptions, columnOptions) {
    const options = [];
    for (let i = 0; i < numOptions; i++) {
      options.push({
        text: columnOptions[i].buildingName,
        value:columnOptions[i].buildingId,
      });
    }
    return options;
  }
  async openPicker(numColumns = 1, numOptions = this.buildings.length, columnOptions = this.buildings) {
    const picker = await this.picker.create({
      columns: this.getColumns(numColumns, numOptions, columnOptions),
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '确认',
          handler: (value) => {
            this.option = '';
            this.option = value.col.text;
            this.buildingName = value.col.text;
            this.buildingId = value.col.value;
            this.selectUnit();
            this.cd.detectChanges();
          }
        }
      ]
    });
    console.log('option', this.option);
    await picker.present();
  }

  getColumns1(numColumns, numOptions, columnOptions) {
    const columns = [];
    for (let i = 0; i < numColumns; i++) {
      columns.push({
        name: `col`,
        options: this.getColumnOptions1(i, numOptions, columnOptions)
      });
    }
    return columns;
  }
  getColumnOptions1(columnIndex, numOptions, columnOptions) {
    const options = [];
    for (let i = 0; i < numOptions; i++) {
      options.push({
        text: columnOptions[i].unitName,
        value:columnOptions[i].unitId,
      });
    }
    return options;
  }
  async openUnit(numColumns = 1, numOptions = this.unitList.length, columnOptions = this.unitList) {
    if (this.unitList.length > 0){
      const picker = await this.picker.create({
        columns: this.getColumns1(numColumns, numOptions, columnOptions),
        buttons: [
          {
            text: '取消',
            role: 'cancel'
          },
          {
            text: '确认',
            handler: (value) => {
              this.option1 = '';
              this.option1 = value.col.text;
              this.unitName = value.col.text;
              this.unitId = value.col.value;
              this.selectHouse();
              this.cd.detectChanges();
            }
          }
        ]
      });
      console.log('option1', this.option1);
      await picker.present();
    } else {
      this.nativeService.showAlert('请先选择楼栋号', '确定');
    }
  }
  async onPageDidLeave(){
    //离开页面时关闭时间选择器
    const backdrop = document.getElementsByTagName('ion-picker');
    console.log('时间选择器'+backdrop);
    for (let i = 0; i < backdrop.length; i++) {
      backdrop[i].setAttribute('style', 'display:none');
    }
    this.modalCtrl.dismiss();
  }
  getColumns2(numColumns, numOptions, columnOptions) {
    const columns = [];
    for (let i = 0; i < numColumns; i++) {
      columns.push({
        name: `col`,
        options: this.getColumnOptions2(i, numOptions, columnOptions)
      });
    }
    return columns;
  }
  getColumnOptions2(columnIndex, numOptions, columnOptions) {
    const options = [];
    for (let i = 0; i < numOptions; i++) {
      options.push({
        text: columnOptions[i].house,
        value:columnOptions[i].houseId,
      });
    }
    return options;
  }
  async openHouse(numColumns = 1, numOptions = this.houseList.length, columnOptions = this.houseList) {
    if (this.houseList.length > 0) {
      const picker = await this.picker.create({
        columns: this.getColumns2(numColumns, numOptions, columnOptions),
        buttons: [
          {
            text: '取消',
            role: 'cancel'
          },
          {
            text: '确认',
            handler: (value) => {
              this.option2 = '';
              this.option2 = value.col.text;
              this.houseId = value.col.value;
              this.house = value.col.text;
              for (let item of this.houseList){
                if (item.houseId == this.houseId){
                  this.getAddress(this.address);
                }
              }
              this.cd.detectChanges();
            }
          }
        ]
      });
      console.log('option2', this.option2);
      await picker.present();
    } else {
      this.nativeService.showAlert('请先选择单元号', '确定');
    }
  }

  // 获取小区经纬度
  async getAddress(address) {
    var lnglat;
    AMap.plugin(["AMap.Geocoder"], function() {
      var geocoder = new AMap.Geocoder({
        city: "",
      });
      geocoder.getLocation(address, function(status, result) {
        console.log('map result = ');
        console.log(result);
        lnglat = result.geocodes[0].location
        var addressComponent;
        addressComponent = result.geocodes[0].addressComponent;
        console.log(lnglat);
        document.getElementsByClassName('latitude-and-longitude')[0].innerHTML = result.geocodes[0].location;
        document.getElementsByClassName('province')[0].innerHTML = addressComponent.province;
        document.getElementsByClassName('city')[0].innerHTML = addressComponent.city;
        document.getElementsByClassName('district')[0].innerHTML = addressComponent.district;
      });
    });
  }
  async getFilter(selectData: any) {
    console.log(selectData);
    this.haveBasement = selectData;
  }

  async submit() {
    const residential = document.getElementsByClassName('latitude-and-longitude')[0].innerHTML;
    const a = residential.split(",");
    const province = document.getElementsByClassName('province')[0].innerHTML;
    const city = document.getElementsByClassName('city')[0].innerHTML;
    const district = document.getElementsByClassName('district')[0].innerHTML;
    if (this.buildings && !this.buildingId) {
      this.nativeService.showAlert('请选择楼栋!', '确定');
    } else if (this.unitList && !this.unitId) {
      this.nativeService.showAlert('请选择单元!', '确定');
    } else if (this.houseList && !this.houseId) {
      this.nativeService.showAlert('请选择房号!', '确定');
    } else if (!this.resiArea) {
      this.nativeService.showAlert('建筑面积不能为空!', '确定');
    }  else if (!this.floorArea && this.floorArea != '0') {
      this.nativeService.showAlert('地上面积不能为空!', '确定');
    }  else if (!this.undergroundArea && this.undergroundArea != '0') {
      this.nativeService.showAlert('地下面积不能为空!', '确定');
    }  else if (!this.builtYear) {
      this.nativeService.showAlert('建成年份不能为空!', '确定');
    }  else {
      let userInfo: UserInfo = await this.storage.read(StorageKey.PERSON_INFO);
      userInfo = userInfo ? userInfo : {};
      let time = new Date(this.builtYear).getFullYear();
      console.log(time+'');
      const param = {
        userId: JSON.stringify(userInfo.userId),
        latitude: a[1],
        longitude: a[0],
        city: this.city,
        name: this.name,
        address: this.address + this.buildingName + this.unitName + this.house,
        buildingName: this.buildingName,
        unitName: this.unitName,
        house: this.house,
        square: this.floorArea,
        communityId: this.communityId,
        em: '1',
        summaryId: this.summaryId,
        buildYear: new Date(this.builtYear).getFullYear() + '',
      };
      console.log('打印再次评估询价传参');
      console.log(param);
      const info = await this.httpService.post(API.APPLY_GETASSESS, param, false);
      console.log('打印再次评估询价返回data');
      console.log(info);
      if (info){
        this.onlineEvaluation = info.salePrice;
        this.maxCreditAvailable = info.maxCreditLimit;
        this.builtYear = info.buildYear;
        console.log(this.address);
        this.modalCtrl.dismiss();
        if (this.flag == 'select'){
          this.router.navigate(['/property-information'], {
            queryParams: {
              resiProivnce: province, //省
              resiCity: city, // 小区所在市
              restDistrict: district, // 小区所在区
              resiAdd: this.address+this.buildingName + this.unitName + this.house,
              resiLongitutd: a[1] ,// 小区经度
              resiLatitutd: a[0],// 小区纬度
              houseBuilding: this.buildingName, // 所在楼栋
              houseUnit: this.unitName, // 所在单元
              houseNumber: this.house, // 所在户
              resiArea: this.resiArea, // 面积
              haveBasement: this.haveBasement, // 是否有地下室（1:是 0:否） int
              floorArea: this.floorArea, // 地上面积 double
              undergroundArea: this.undergroundArea, // 地下面积 double
              builtYear: this.builtYear, // 建成年份 int
              houseLocated: this.address ,// 房地产坐落
              summaryId: this.summaryId,
              serialNo: this.serialNo,
              onlineEvaluation: this.onlineEvaluation,
              maxCreditAvailable: this.maxCreditAvailable,
              inputTime: this.inputTime,
              communityId: this.communityId, // 小区编号
              changingFlag: '1',
            }
          })
        } else if (this.flag == 'trial'){
          this.router.navigate(['/evaluation-inquiry'], {
            queryParams: {
              name: this.name, // 小区名
              resiCity: city, // 小区所在市
              restDistrict: district, // 小区所在区
              resiProivnce: province, //省
              resiAdd: this.address,  // 小区地址
              resiLongitutd: a[1] ,// 小区经度
              resiLatitutd: a[0],// 小区纬度
              houseBuilding: this.buildingName, // 所在楼栋
              houseUnit: this.unitName, // 所在单元
              houseNumber: this.house, // 所在户
              resiArea: this.resiArea, // 面积房屋面积
              haveBasement: this.haveBasement, // 是否有地下室（1:是 0:否） int
              floorArea: this.floorArea, // 地上面积 double
              undergroundArea: this.undergroundArea, // 地下面积 double
              builtYear: this.builtYear, // 建成年份 int
              houseLocated: this.address + '' + this.buildingName + this.unitName + this.house,// 区域
              summaryId: this.summaryId,
              serialNo: this.serialNo,
              onlineEvaluation: this.onlineEvaluation,  // 评估价
              maxCreditAvailable: this.maxCreditAvailable, // 预授信额度
              communityId: this.communityId, // 小区编号

            }
          })
        }
        else {
          this.router.navigate(['/estate-information'], {
            queryParams: {
              resiProivnce: province, //省
              resiCity: city, // 小区所在市
              restDistrict: district, // 小区所在区
              resiAdd: this.address+this.buildingName + this.unitName + this.house,  // 小区地址
              houseBuilding: this.buildingName, // 所在楼栋
              houseUnit: this.unitName, // 所在单元
              houseNumber: this.house, // 所在户
              resiArea: this.resiArea, // 面积
              resiLongitutd: a[1] ,// 小区经度
              resiLatitutd: a[0],// 小区纬度
              haveBasement: this.haveBasement, // 是否有地下室（1:是 0:否） int
              floorArea: this.floorArea, // 地上面积 double
              undergroundArea: this.undergroundArea, // 地下面积 double
              builtYear: this.builtYear, // 建成年份 int
              houseLocated: this.address ,// 房地产坐落
              summaryId: this.summaryId,
              serialNo: this.serialNo,
              onlineEvaluation: this.onlineEvaluation,
              maxCreditAvailable: this.maxCreditAvailable,
              communityId: this.communityId, // 小区编号
              urlFlag: '1',
            }
          })
        }
      }
    }
  }

  async back() {
    this.modalCtrl.dismiss();
    let select = await this.modalCtrl.create({
      component: SelectCommunityComponent,
      cssClass: 'toast',
      showBackdrop: true,
      backdropDismiss: true,
      componentProps: {
        address: this.address,
        name: this.name,
        city:  this.city,
        communityId:  this.communityId,
        summaryId: this.summaryId,
        code: this.code,
        serialNo: this.serialNo,
        province: this.province,
        resiCity: this.resiCity,
        restDistrict: this.restDistrict,
      }
    });
    select.present();
  }

  // 建筑面积计算
  AreaTest(floorArea) {
    if (!floorArea) {
      return;
    }
    if (!this.resiArea) {
      this.nativeService.showAlert('请先输入建筑面积!', '确定');
      this.floorArea = '';
    } else if (parseFloat(floorArea) > parseFloat(this.resiArea)) {
      console.log(floorArea);
      console.log(this.resiArea);
      this.nativeService.showAlert('地下面积不可大于建筑面积!', '确定');
      this.floorArea = '';
    } else {
      this.undergroundArea = this.resiArea - floorArea;
    }
  }

  AreaTest1(undergroundArea) {
    if (!undergroundArea) {
      return;
    }
    if (!this.resiArea) {
      this.nativeService.showAlert('请先输入建筑面积!', '确定');
      this.undergroundArea = '';
    } else if (parseFloat(undergroundArea) > parseFloat(this.resiArea)) {
      this.nativeService.showAlert('地下面积不可大于建筑面积!', '确定');
      this.undergroundArea = '';
    } else {
      this.floorArea = this.resiArea - undergroundArea;
    }
  }

}
